package com.gitee.chili.leisure.message;

import com.gitee.chili.leisure.ResponseCode;
import com.gitee.chili.leisure.RoomManager;
import com.gitee.chili.leisure.core.AbstractDefaultMessage;
import com.gitee.chili.leisure.core.Packet;
import com.gitee.chili.leisure.exception.NotFoundMemberException;
import com.gitee.chili.leisure.game.Player;
import com.gitee.chili.leisure.model.HallModel;
import com.gitee.chili.leisure.model.MessageCmdEnum;
import com.gitee.chili.leisure.util.AuxiliaryChannel;
import com.google.protobuf.InvalidProtocolBufferException;
import io.netty.channel.Channel;

import java.util.Objects;
import java.util.Optional;

/**
 * 投票解散房间
 *
 * @author week solider
 * @since 2020.09.11
 */
public class VoteDissolvedRoom extends AbstractDefaultMessage {


    public VoteDissolvedRoom(Packet packet, Channel channel) {
        super(packet, channel);
    }

    @Override
    protected void decoder(byte[] body) throws InvalidProtocolBufferException {
        HallModel.VoteToDissolvedRoomCmd voteToDissolvedRoom = HallModel.VoteToDissolvedRoomCmd.parseFrom(body);
        asserts(Objects.isNull(voteToDissolvedRoom), cmd -> AuxiliaryChannel.errorMessage(getChannel(), cmd, ResponseCode.FAIL));
    }

    @Override
    public Packet parseBody() {
        HallModel.NotifyDissolvedRoomForVoteCmd.Builder builder = HallModel.NotifyDissolvedRoomForVoteCmd.newBuilder();

        Optional<? extends Player> optional = RoomManager.obtain(getRoomNum())
                .getPlayers().stream().filter(p -> p.getUserId().equals(getMemberId())).findFirst();

        asserts(!optional.isPresent(), cmd -> AuxiliaryChannel.errorMessage(getChannel(), cmd, ResponseCode.CACHE_MISS));

        if(!optional.isPresent()){
            AuxiliaryChannel.errorMessage(getChannel(), getPacket().getCmd(), ResponseCode.CACHE_MISS);
            throw new NotFoundMemberException("获取玩家信息，缓存丢失");
        }

        Player player = optional.get();

        builder.setSponsorSeatId(player.getPosition()).setVoteEndTime(60 * 1000L);

        return Packet.newPacket(MessageCmdEnum.Command.NOTIFY_DISSOLVED_ROOM_FOR_VOTE, builder.build().toByteArray());
    }
}
